<template>
  <div class="bills-page">
    <div class="page-header">
      <div class="container">
        <h1 class="page-title">费用查询</h1>
        <el-breadcrumb separator="/">
          <el-breadcrumb-item :to="{ path: '/portal' }">首页</el-breadcrumb-item>
          <el-breadcrumb-item :to="{ path: '/portal/patient' }">患者服务</el-breadcrumb-item>
          <el-breadcrumb-item>费用查询</el-breadcrumb-item>
        </el-breadcrumb>
      </div>
    </div>
    
    <div class="container main-content">
      <!-- 费用统计卡片 -->
      <div class="stats-section">
        <el-row :gutter="20">
          <el-col :xs="24" :sm="12" :md="6" :lg="6">
            <el-card class="stat-card" shadow="hover">
              <div class="stat-content">
                <div class="stat-icon total">
                  <el-icon><Money /></el-icon>
                </div>
                <div class="stat-info">
                  <div class="stat-value">¥{{ totalAmount.toFixed(2) }}</div>
                  <div class="stat-label">总费用</div>
                </div>
              </div>
            </el-card>
          </el-col>
          
          <el-col :xs="24" :sm="12" :md="6" :lg="6">
            <el-card class="stat-card" shadow="hover">
              <div class="stat-content">
                <div class="stat-icon paid">
                  <el-icon><CircleCheck /></el-icon>
                </div>
                <div class="stat-info">
                  <div class="stat-value">¥{{ paidAmount.toFixed(2) }}</div>
                  <div class="stat-label">已支付</div>
                </div>
              </div>
            </el-card>
          </el-col>
          
          <el-col :xs="24" :sm="12" :md="6" :lg="6">
            <el-card class="stat-card" shadow="hover">
              <div class="stat-content">
                <div class="stat-icon unpaid">
                  <el-icon><Warning /></el-icon>
                </div>
                <div class="stat-info">
                  <div class="stat-value">¥{{ unpaidAmount.toFixed(2) }}</div>
                  <div class="stat-label">待支付</div>
                </div>
              </div>
            </el-card>
          </el-col>
          
          <el-col :xs="24" :sm="12" :md="6" :lg="6">
            <el-card class="stat-card" shadow="hover">
              <div class="stat-content">
                <div class="stat-icon count">
                  <el-icon><Document /></el-icon>
                </div>
                <div class="stat-info">
                  <div class="stat-value">{{ billCount }}</div>
                  <div class="stat-label">账单数量</div>
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>
      
      <el-card class="search-card">
        <div class="search-header">
          <h3 class="search-title">查询条件</h3>
        </div>
        
        <el-form :inline="true" :model="searchForm" ref="searchFormRef" class="search-form">
          <el-form-item label="费用时间">
            <el-date-picker
              v-model="dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="YYYY-MM-DD"
              :shortcuts="dateShortcuts"
              style="width: 320px"
            />
          </el-form-item>
          
          <el-form-item label="费用类型">
            <el-select v-model="searchForm.billType" placeholder="请选择费用类型" clearable style="width: 150px">
              <el-option label="全部类型" value="" />
              <el-option label="挂号费" value="registration" />
              <el-option label="诊疗费" value="consultation" />
              <el-option label="检查费" value="examination" />
              <el-option label="化验费" value="laboratory" />
              <el-option label="药品费" value="medication" />
              <el-option label="治疗费" value="treatment" />
              <el-option label="手术费" value="surgery" />
              <el-option label="材料费" value="materials" />
            </el-select>
          </el-form-item>
          
          <el-form-item label="支付状态">
            <el-select v-model="searchForm.paymentStatus" placeholder="请选择状态" clearable style="width: 120px">
              <el-option label="全部状态" value="" />
              <el-option label="已支付" value="paid" />
              <el-option label="待支付" value="unpaid" />
              <el-option label="部分支付" value="partial" />
              <el-option label="已退费" value="refunded" />
            </el-select>
          </el-form-item>
          
          <el-form-item>
            <el-button type="primary" @click="handleSearch" :loading="loading">
              <el-icon><Search /></el-icon> 查询
            </el-button>
            <el-button @click="handleReset">
              <el-icon><RefreshLeft /></el-icon> 重置
            </el-button>
          </el-form-item>
        </el-form>
      </el-card>
      
      <el-card class="bills-card">
        <div class="bills-header">
          <h3 class="bills-title">费用账单列表</h3>
          <div class="bills-actions">
            <el-button type="success" @click="handleExportBills">
              <el-icon><Download /></el-icon> 导出账单
            </el-button>
          </div>
        </div>
        
        <el-table 
          :data="billsList" 
          v-loading="loading"
          style="width: 100%"
          stripe
          @row-click="handleRowClick"
          :summary-method="getSummaries"
          show-summary
        >
          <el-table-column prop="billDate" label="费用日期" width="120" sortable>
            <template #default="scope">
              {{ formatDate(scope.row.billDate) }}
            </template>
          </el-table-column>
          
          <el-table-column prop="billNo" label="账单号" width="160" />
          
          <el-table-column prop="billType" label="费用类型" width="100">
            <template #default="scope">
              <el-tag size="small" :type="getBillTypeColor(scope.row.billType)">
                {{ getBillTypeText(scope.row.billType) }}
              </el-tag>
            </template>
          </el-table-column>
          
          <el-table-column prop="itemName" label="费用项目" show-overflow-tooltip />
          
          <el-table-column prop="department" label="产生科室" width="120" />
          
          <el-table-column prop="amount" label="费用金额" width="120" align="right">
            <template #default="scope">
              <span class="amount-text">¥{{ scope.row.amount.toFixed(2) }}</span>
            </template>
          </el-table-column>
          
          <el-table-column prop="paymentStatus" label="支付状态" width="100">
            <template #default="scope">
              <el-tag :type="getPaymentStatusType(scope.row.paymentStatus)">
                {{ getPaymentStatusText(scope.row.paymentStatus) }}
              </el-tag>
            </template>
          </el-table-column>
          
          <el-table-column prop="paymentMethod" label="支付方式" width="100">
            <template #default="scope">
              {{ scope.row.paymentMethod || '-' }}
            </template>
          </el-table-column>
          
          <el-table-column label="操作" width="240" fixed="right">
            <template #default="scope">
              <div class="action-buttons">
                <el-button size="small" type="primary" @click.stop="handleViewDetail(scope.row)">
                  查看详情
                </el-button>
                <el-button 
                  size="small" 
                  type="success" 
                  @click.stop="handlePayment(scope.row)"
                  v-if="scope.row.paymentStatus === 'unpaid'"
                >
                  立即支付
                </el-button>
                <el-button 
                  size="small" 
                  type="info" 
                  @click.stop="handleDownloadInvoice(scope.row)"
                  v-if="scope.row.paymentStatus === 'paid'"
                >
                  下载发票
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
        
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          class="pagination"
        />
      </el-card>
    </div>
    
    <!-- 费用详情弹窗 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="费用详情"
      width="800px"
      :close-on-click-modal="false"
    >
      <div v-if="currentBill" class="bill-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="账单号">
            {{ currentBill.billNo }}
          </el-descriptions-item>
          <el-descriptions-item label="费用日期">
            {{ formatDate(currentBill.billDate) }}
          </el-descriptions-item>
          <el-descriptions-item label="费用类型">
            <el-tag size="small" :type="getBillTypeColor(currentBill.billType)">
              {{ getBillTypeText(currentBill.billType) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="产生科室">
            {{ currentBill.department }}
          </el-descriptions-item>
          <el-descriptions-item label="费用金额">
            <span class="amount-highlight">¥{{ currentBill.amount.toFixed(2) }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="支付状态">
            <el-tag :type="getPaymentStatusType(currentBill.paymentStatus)">
              {{ getPaymentStatusText(currentBill.paymentStatus) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="支付方式" v-if="currentBill.paymentMethod">
            {{ currentBill.paymentMethod }}
          </el-descriptions-item>
          <el-descriptions-item label="支付时间" v-if="currentBill.paymentTime">
            {{ formatDateTime(currentBill.paymentTime) }}
          </el-descriptions-item>
        </el-descriptions>
        
        <div class="detail-section">
          <h4>费用明细</h4>
          <div class="content-box">
            <el-table :data="currentBill.items || []" size="small">
              <el-table-column prop="itemName" label="项目名称" />
              <el-table-column prop="quantity" label="数量" width="80" align="center" />
              <el-table-column prop="unitPrice" label="单价" width="100" align="right">
                <template #default="scope">
                  ¥{{ scope.row.unitPrice.toFixed(2) }}
                </template>
              </el-table-column>
              <el-table-column prop="subtotal" label="小计" width="100" align="right">
                <template #default="scope">
                  ¥{{ scope.row.subtotal.toFixed(2) }}
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
        
        <div class="detail-section">
          <h4>备注信息</h4>
          <div class="content-box">
            {{ currentBill.remarks || '无' }}
          </div>
        </div>
      </div>
      
      <template #footer>
        <el-button @click="detailDialogVisible = false">关闭</el-button>
        <el-button 
          type="success" 
          @click="handlePaymentInDetail"
          v-if="currentBill && currentBill.paymentStatus === 'unpaid'"
        >
          立即支付
        </el-button>
        <el-button 
          type="primary" 
          @click="handleDownloadInvoiceInDetail"
          v-if="currentBill && currentBill.paymentStatus === 'paid'"
        >
          下载发票
        </el-button>
      </template>
    </el-dialog>
    
    <!-- 支付弹窗 -->
    <el-dialog
      v-model="paymentDialogVisible"
      title="费用支付"
      width="500px"
      :close-on-click-modal="false"
    >
      <div v-if="paymentBill" class="payment-content">
        <div class="payment-info">
          <p><strong>账单号：</strong>{{ paymentBill.billNo }}</p>
          <p><strong>费用项目：</strong>{{ paymentBill.itemName }}</p>
          <p><strong>支付金额：</strong><span class="amount-highlight">¥{{ paymentBill.amount.toFixed(2) }}</span></p>
        </div>
        
        <el-form :model="paymentForm" label-width="100px">
          <el-form-item label="支付方式">
            <el-radio-group v-model="paymentForm.method">
              <el-radio value="alipay">支付宝</el-radio>
              <el-radio value="wechat">微信支付</el-radio>
              <el-radio value="bank">银行卡</el-radio>
              <el-radio value="cash">现金</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
      </div>
      
      <template #footer>
        <el-button @click="paymentDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleConfirmPayment" :loading="paymentLoading">
          确认支付
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/stores/user'
import { patientAPI } from '@/utils/api'
import { format } from 'date-fns'
import { Search, RefreshLeft, Money, CircleCheck, Warning, Document, Download } from '@element-plus/icons-vue'

const router = useRouter()
const userStore = useUserStore()

// 数据状态
const loading = ref(false)
const paymentLoading = ref(false)
const billsList = ref([])
const detailDialogVisible = ref(false)
const paymentDialogVisible = ref(false)
const currentBill = ref(null)
const paymentBill = ref(null)
const currentPatient = ref(null)

// 搜索表单
const searchForm = reactive({
  billType: '',
  paymentStatus: ''
})

const dateRange = ref([])

// 支付表单
const paymentForm = reactive({
  method: 'alipay'
})

// 分页信息
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 费用统计
const totalAmount = computed(() => {
  return billsList.value.reduce((sum, bill) => sum + bill.amount, 0)
})

const paidAmount = computed(() => {
  return billsList.value.filter(bill => bill.paymentStatus === 'paid')
    .reduce((sum, bill) => sum + bill.amount, 0)
})

const unpaidAmount = computed(() => {
  return billsList.value.filter(bill => bill.paymentStatus === 'unpaid')
    .reduce((sum, bill) => sum + bill.amount, 0)
})

const billCount = computed(() => {
  return billsList.value.length
})

// 计算费用统计
const billsStats = computed(() => {
  const stats = {
    totalAmount: 0,
    paidAmount: 0,
    unpaidAmount: 0,
    billsCount: billsList.value.length
  }
  
  billsList.value.forEach(bill => {
    stats.totalAmount += bill.totalAmount || 0
    if (bill.paymentStatus === 'paid') {
      stats.paidAmount += bill.totalAmount || 0
    } else {
      stats.unpaidAmount += bill.totalAmount || 0
    }
  })
  
  return stats
})

// 日期快捷选项
const dateShortcuts = [
  {
    text: '最近一周',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
      return [start, end]
    }
  },
  {
    text: '最近一个月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
      return [start, end]
    }
  },
  {
    text: '最近三个月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
      return [start, end]
    }
  }
]

// 获取费用类型颜色
const getBillTypeColor = (type) => {
  const colors = {
    'registration': 'primary',
    'consultation': 'success',
    'examination': 'warning',
    'laboratory': 'info',
    'medication': 'danger',
    'treatment': '',
    'surgery': 'danger',
    'materials': 'warning'
  }
  return colors[type] || ''
}

// 获取费用类型文本
const getBillTypeText = (type) => {
  const texts = {
    'registration': '挂号费',
    'consultation': '诊疗费',
    'examination': '检查费',
    'laboratory': '化验费',
    'medication': '药品费',
    'treatment': '治疗费',
    'surgery': '手术费',
    'materials': '材料费'
  }
  return texts[type] || type
}

// 获取支付状态类型
const getPaymentStatusType = (status) => {
  const types = {
    'paid': 'success',
    'unpaid': 'danger',
    'partial': 'warning',
    'refunded': 'info'
  }
  return types[status] || 'info'
}

// 获取支付状态文本
const getPaymentStatusText = (status) => {
  const texts = {
    'paid': '已支付',
    'unpaid': '待支付',
    'partial': '部分支付',
    'refunded': '已退费'
  }
  return texts[status] || '未知'
}

// 格式化日期
const formatDate = (date) => {
  if (!date) return '-'
  try {
    return format(new Date(date), 'yyyy-MM-dd')
  } catch {
    return date
  }
}

// 格式化日期时间
const formatDateTime = (date) => {
  if (!date) return '-'
  try {
    return format(new Date(date), 'yyyy-MM-dd HH:mm:ss')
  } catch {
    return date
  }
}

// 表格合计行
const getSummaries = (param) => {
  const { columns, data } = param
  const sums = []
  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = '合计'
      return
    }
    if (column.property === 'amount') {
      const values = data.map(item => Number(item[column.property]))
      if (!values.every(value => Number.isNaN(value))) {
        sums[index] = `¥${values.reduce((prev, curr) => {
          const value = Number(curr)
          if (!Number.isNaN(value)) {
            return prev + curr
          } else {
            return prev
          }
        }, 0).toFixed(2)}`
      } else {
        sums[index] = '-'
      }
    } else {
      sums[index] = ''
    }
  })
  return sums
}

// 获取当前患者信息
const getCurrentPatient = async () => {
  try {
    const currentUserId = userStore.userInfo?.id || userStore.userInfo?._id
    console.log('当前用户ID:', currentUserId)
    
    if (!currentUserId) {
      throw new Error('未找到当前用户ID')
    }
    
    // 通过用户ID获取患者信息
    const res = await patientAPI.getPatients({ userId: currentUserId })
    console.log('患者查询响应:', res)
    
    if (res.success && res.data && res.data.patients && res.data.patients.length > 0) {
      currentPatient.value = res.data.patients[0]
      console.log('找到当前患者:', currentPatient.value)
      return currentPatient.value
    } else {
      throw new Error('未找到对应的患者信息')
    }
  } catch (error) {
    console.error('获取患者信息失败:', error)
    ElMessage.error('获取患者信息失败，请联系管理员')
    throw error
  }
}

// 加载费用账单数据
const loadBills = async () => {
  try {
    loading.value = true
    
    // 如果还没有患者信息，先获取
    if (!currentPatient.value) {
      await getCurrentPatient()
    }
    
    // 确保有患者信息
    if (!currentPatient.value) {
      ElMessage.error('未找到患者信息，无法加载费用账单')
      return
    }
    
    const params = {
      page: pagination.currentPage,
      pageSize: pagination.pageSize,
      patientId: currentPatient.value?.id || currentPatient.value?._id
    }
    
    console.log('查询费用账单参数:', params)
    
    // 添加搜索条件
    if (dateRange.value && dateRange.value.length === 2) {
      params.startDate = dateRange.value[0]
      params.endDate = dateRange.value[1]
    }
    
    if (searchForm.billType) {
      params.billType = searchForm.billType
    }
    
    if (searchForm.paymentStatus) {
      params.paymentStatus = searchForm.paymentStatus
    }
    
    const res = await patientAPI.getBills(params)
    
    if (res.success && res.data) {
      billsList.value = res.data.bills || res.data.items || []
      pagination.total = res.data.total || 0
    } else {
      // 如果API请求失败，使用模拟数据
      loadMockData()
    }
  } catch (error) {
    console.error('加载费用账单失败:', error)
    // 加载模拟数据
    loadMockData()
  } finally {
    loading.value = false
  }
}

// 加载模拟数据
const loadMockData = () => {
  const mockBills = [
    {
      id: '1',
      billNo: 'BILL2024011501',
      billDate: '2024-01-15',
      billType: 'registration',
      itemName: '普通门诊挂号费',
      department: '内科',
      amount: 15.00,
      paymentStatus: 'paid',
      paymentMethod: '支付宝',
      paymentTime: '2024-01-15 09:30:00',
      items: [
        { itemName: '普通门诊挂号费', quantity: 1, unitPrice: 15.00, subtotal: 15.00 }
      ],
      remarks: '内科普通门诊挂号'
    },
    {
      id: '2',
      billNo: 'BILL2024011502',
      billDate: '2024-01-15',
      billType: 'examination',
      itemName: '血常规检查',
      department: '检验科',
      amount: 45.00,
      paymentStatus: 'paid',
      paymentMethod: '微信支付',
      paymentTime: '2024-01-15 10:15:00',
      items: [
        { itemName: '血常规检查', quantity: 1, unitPrice: 45.00, subtotal: 45.00 }
      ],
      remarks: '血常规检查费用'
    },
    {
      id: '3',
      billNo: 'BILL2024011503',
      billDate: '2024-01-15',
      billType: 'medication',
      itemName: '药品费用',
      department: '药房',
      amount: 128.50,
      paymentStatus: 'unpaid',
      paymentMethod: '',
      paymentTime: '',
      items: [
        { itemName: '阿莫西林胶囊', quantity: 2, unitPrice: 25.50, subtotal: 51.00 },
        { itemName: '感冒颗粒', quantity: 3, unitPrice: 15.50, subtotal: 46.50 },
        { itemName: '维生素C片', quantity: 1, unitPrice: 31.00, subtotal: 31.00 }
      ],
      remarks: '处方药品费用'
    },
    {
      id: '4',
      billNo: 'BILL2024011204',
      billDate: '2024-01-12',
      billType: 'examination',
      itemName: '胸部X线检查',
      department: '放射科',
      amount: 85.00,
      paymentStatus: 'paid',
      paymentMethod: '银行卡',
      paymentTime: '2024-01-12 14:20:00',
      items: [
        { itemName: '胸部X线检查', quantity: 1, unitPrice: 85.00, subtotal: 85.00 }
      ],
      remarks: '胸部X线平片检查'
    },
    {
      id: '5',
      billNo: 'BILL2024011005',
      billDate: '2024-01-10',
      billType: 'consultation',
      itemName: '专家门诊诊疗费',
      department: '外科',
      amount: 50.00,
      paymentStatus: 'paid',
      paymentMethod: '支付宝',
      paymentTime: '2024-01-10 11:00:00',
      items: [
        { itemName: '专家门诊诊疗费', quantity: 1, unitPrice: 50.00, subtotal: 50.00 }
      ],
      remarks: '外科专家门诊费用'
    }
  ]
  
  billsList.value = mockBills
  pagination.total = mockBills.length
}

// 搜索处理
const handleSearch = () => {
  pagination.currentPage = 1
  loadBills()
}

// 重置搜索
const handleReset = () => {
  searchForm.billType = ''
  searchForm.paymentStatus = ''
  dateRange.value = []
  pagination.currentPage = 1
  loadBills()
}

// 分页处理
const handleSizeChange = (val) => {
  pagination.pageSize = val
  pagination.currentPage = 1
  loadBills()
}

const handleCurrentChange = (val) => {
  pagination.currentPage = val
  loadBills()
}

// 行点击处理
const handleRowClick = (row) => {
  handleViewDetail(row)
}

// 查看详情
const handleViewDetail = (row) => {
  currentBill.value = row
  detailDialogVisible.value = true
}

// 支付处理
const handlePayment = (row) => {
  paymentBill.value = row
  paymentForm.method = 'alipay'
  paymentDialogVisible.value = true
}

// 详情中支付
const handlePaymentInDetail = () => {
  detailDialogVisible.value = false
  handlePayment(currentBill.value)
}

// 确认支付
const handleConfirmPayment = async () => {
  try {
    paymentLoading.value = true
    
    // 模拟支付处理
    await new Promise(resolve => setTimeout(resolve, 2000))
    
    // 更新支付状态
    paymentBill.value.paymentStatus = 'paid'
    paymentBill.value.paymentMethod = getPaymentMethodText(paymentForm.method)
    paymentBill.value.paymentTime = new Date().toISOString()
    
    ElMessage.success('支付成功！')
    paymentDialogVisible.value = false
  } catch (error) {
    console.error('支付失败:', error)
    ElMessage.error('支付失败，请重试')
  } finally {
    paymentLoading.value = false
  }
}

// 获取支付方式文本
const getPaymentMethodText = (method) => {
  const texts = {
    'alipay': '支付宝',
    'wechat': '微信支付',
    'bank': '银行卡',
    'cash': '现金'
  }
  return texts[method] || method
}

// 下载发票
const handleDownloadInvoice = (row) => {
  if (row.paymentStatus !== 'paid') {
    ElMessage.warning('只有已支付的账单才能下载发票')
    return
  }
  
  ElMessage.success('发票下载中...')
  downloadInvoice(row.billNo)
}

// 详情中下载发票
const handleDownloadInvoiceInDetail = () => {
  if (currentBill.value) {
    handleDownloadInvoice(currentBill.value)
  }
}

// 下载发票文件
const downloadInvoice = async (billNo) => {
  try {
    // 模拟下载
    const link = document.createElement('a')
    link.href = `data:text/plain;charset=utf-8,发票号: ${billNo}`
    link.download = `发票_${billNo}.pdf`
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
  } catch (error) {
    console.error('下载失败:', error)
    ElMessage.error('下载失败，请重试')
  }
}

// 导出账单
const handleExportBills = () => {
  ElMessage.success('账单导出中...')
  // 这里应该调用导出API
  exportBills()
}

// 导出账单文件
const exportBills = async () => {
  try {
    // 模拟导出
    const csvContent = billsList.value.map(bill => 
      `${bill.billNo},${bill.billDate},${getBillTypeText(bill.billType)},${bill.itemName},${bill.amount},${getPaymentStatusText(bill.paymentStatus)}`
    ).join('\n')
    
    const link = document.createElement('a')
    link.href = `data:text/csv;charset=utf-8,\uFEFF账单号,费用日期,费用类型,费用项目,金额,支付状态\n${csvContent}`
    link.download = `费用账单_${format(new Date(), 'yyyyMMdd')}.csv`
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败，请重试')
  }
}

// 检查用户是否已登录并初始化数据
onMounted(async () => {
  if (!userStore.isLoggedIn) {
    ElMessage.warning('请先登录后再查看费用账单')
    router.push({
      path: '/portal/login',
      query: { redirect: '/portal/patient/bills' }
    })
    return
  }
  
  // 已登录，先获取患者信息，再加载费用账单数据
  try {
    await getCurrentPatient()
    await loadBills()
  } catch (error) {
    console.error('初始化数据失败:', error)
    // 即使获取患者信息失败，也尝试加载模拟数据
    loadMockData()
  }
})
</script>

<style scoped>
.bills-page {
  background-color: #f5f7fa;
  min-height: 100vh;
  padding-bottom: 40px;
}

.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
}

.page-header {
  background-color: white;
  padding: 20px 0;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
  margin-bottom: 30px;
}

.page-title {
  font-size: 24px;
  color: #333;
  margin: 0 0 10px;
}

.main-content {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.stats-section {
  margin-bottom: 20px;
}

.stat-card {
  height: 120px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.stat-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
}

.stat-content {
  display: flex;
  align-items: center;
  height: 100%;
  padding: 20px;
}

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 20px;
  font-size: 24px;
  color: white;
}

.stat-icon.total {
  background: linear-gradient(45deg, #409EFF, #66B3FF);
}

.stat-icon.paid {
  background: linear-gradient(45deg, #67C23A, #85CE61);
}

.stat-icon.unpaid {
  background: linear-gradient(45deg, #F56C6C, #F78989);
}

.stat-icon.count {
  background: linear-gradient(45deg, #E6A23C, #EEBE77);
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #333;
  margin-bottom: 5px;
}

.stat-label {
  font-size: 14px;
  color: #666;
}

.search-card, .bills-card {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.search-header, .bills-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.search-title, .bills-title {
  font-size: 18px;
  font-weight: 600;
  color: #333;
  margin: 0;
}

.search-form {
  margin-top: 20px;
}

.amount-text {
  color: #E6A23C;
  font-weight: 600;
}

.amount-highlight {
  color: #F56C6C;
  font-size: 18px;
  font-weight: bold;
}

.pagination {
  margin-top: 20px;
  justify-content: center;
}

.bill-detail {
  max-height: 70vh;
  overflow-y: auto;
}

.detail-section {
  margin-top: 20px;
}

.detail-section h4 {
  margin: 0 0 10px 0;
  color: #333;
  font-size: 16px;
  font-weight: 600;
}

.content-box {
  background: #f8f9fa;
  border: 1px solid #e9ecef;
  border-radius: 4px;
  padding: 12px;
  min-height: 40px;
  line-height: 1.5;
}

.payment-content {
  text-align: center;
}

.payment-info {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 20px;
}

.payment-info p {
  margin: 10px 0;
  font-size: 16px;
}

.action-buttons {
  display: flex;
  flex-wrap: wrap;
  gap: 5px;
}

.action-buttons .el-button {
  margin: 0;
}

@media (max-width: 768px) {
  .search-form {
    flex-direction: column;
  }
  
  .search-form :deep(.el-form-item) {
    margin-right: 0;
    margin-bottom: 15px;
  }
  
  .bills-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 15px;
  }
  
  .stat-content {
    padding: 15px;
  }
  
  .stat-icon {
    width: 50px;
    height: 50px;
    margin-right: 15px;
    font-size: 20px;
  }
  
  .stat-value {
    font-size: 20px;
  }
}
</style> 